<?php

namespace app\Hotel\controller;

use think\Controller;

class Room extends Controller
{
    protected $BusinessModel;
    protected $CouponModel;
    protected $GuestModel;
    protected $ReceiveModel;
    protected $OrderModel;
    protected $RoomModel;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->CouponModel = model('Hotel.Coupon.Coupon');
        $this->GuestModel = model('Hotel.Guest');
        $this->ReceiveModel = model('Hotel.Coupon.Receive');
        $this->OrderModel = model('Hotel.Order');
        $this->RoomModel = model('Hotel.Room');
    }

    public function index()
    {
        $page = $this->request->param('page', 0, 'trim');
        $limit = $this->request->param('limit', 10, 'trim');
        $keyword = $this->request->param('keyword', 0, 'trim');
        $order = $this->request->param('order', '', 'trim');
        $orderType = $this->request->param('orderType', 'desc', 'trim');

        $offset = ($page - 1) * $limit;

        if ($limit > 100 || $limit < 1) {
            $limit = 10;
        }

        $where = [];
        $_order = '';

        if (!empty($order)) {
            $_order .= $order . ' ' . $orderType;
        }

        if (!empty($keyword)) {
            $where['name'] = ['LIKE', "%$keyword%"];
        }

        $total = $this->RoomModel
            ->where($where)
            ->count();

        $list  = $this->RoomModel
            ->where($where)
            ->order($_order)
            ->limit($offset, $limit)
            ->select();

        $result = [
            'list' => $list ?? [],
            'total' => $total
        ];

        $this->success('ok', null, $result);
    }

    public function info()
    {
        $rid = $this->request->param('rid', 0, 'trim');

        $room = $this->RoomModel->find($rid);
        if (!$room) {
            $this->error('暂无房间信息');
            exit;
        }

        $where = [
            'roomid' => $rid,
            'status' => ['IN', ['1', '2']],
        ];

        $count = $this->OrderModel->where($where)->count();

        $room['state'] = bcsub($room['total'], $count) <= 0 ? false : true;

        $this->success('返回房间信息', null, $room);
        exit;
    }

    public function add()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        $roomid = $this->request->param('roomid', 0, 'trim');
        $couponid = $this->request->param('couponid', -1, 'trim');
        $starttime = $this->request->param('starttime', 0, 'trim');
        $endtime = $this->request->param('endtime', 0, 'trim');
        $guest = $this->request->param('guest', NULL, 'trim');

        try {
            $starttime = intval($starttime);
            $endtime = intval($endtime);
        } catch (\Throwable $th) {
            $this->error('时间格式错误');
            exit;
        }

        $business = $this->BusinessModel->find($busid);
        if (!$business) {
            $this->error('用户不存在');
            exit;
        }

        $room = $this->RoomModel->find($roomid);
        if (!$room) {
            $this->error('房间不存在');
            exit;
        }

        $where = [
            'roomid' => $roomid,
            'status' => ['IN', '1,2']
        ];
        $count = $this->OrderModel->where($where)->count();
        $newCount = bcsub($room['total'], $count);

        if ($newCount <= 0) {
            $this->error('该房型已全部预约');
            exit;
        }

        $where = [
            'busid' => $busid,
            'receive.cid' => $couponid
        ];

        $receive = null;

        if (intval($couponid) !== -1) {
            $receive = $this->ReceiveModel->with(['coupon'])->where($where)->find();

            if ($receive) {
                if ($receive['status'] == '0') {
                    $this->error('优惠券已失效');
                    exit;
                }
            } else {
                $this->error('优惠券不存在');
                exit;
            }
        }


        // 入住天数
        $days = intval(($endtime - $starttime) / 86400);
        $price = $origin_price = bcmul($room['price'], $days);

        // 查询到了优惠券
        if ($receive) {
            $rate = isset($receive['coupon']['rate']) ? $receive['coupon']['rate'] : 1;
            // 根据折扣计算的新的价格
            $price = bcmul($origin_price, $rate, 2);
        }

        $newMoney = bcsub($business['money'], $price, 2);

        if ($newMoney < 0) {
            $this->error('余额不足，请先充值');
            exit;
        }

        // 开启事务
        $this->OrderModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->ReceiveModel->startTrans();

        $orderData = [
            'busid'        => $busid,
            'roomid'       => $roomid,
            'guest'        => $guest,
            'origin_price' => $origin_price,
            'price'        => $price,
            'starttime'    => $starttime,
            'endtime'      => $endtime,
            'status'       => '1',
            'couponid'     => $couponid ? $couponid : null
        ];

        $orderRes = $this->OrderModel->save($orderData);

        if ($orderRes === false) {
            $this->error($this->OrderModel->getError());
            exit;
        }

        $busData = [
            'id'    => $busid,
            'money' => $newMoney,
        ];

        $busRes = $this->BusinessModel->isUpdate(true)->save($busData);

        if ($busRes === false) {
            $this->OrderModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        if ($orderData['couponid']) {
            $receiveData = [
                'id' => $couponid,
                'status' => '0' // 将状态改为已使用
            ];

            $receiveRes = $this->ReceiveModel->isUpdate(true)->save($receiveData);

            if ($receiveRes === false) {
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ReceiveModel->getError());
                exit;
            }
        }

        if ($orderRes === false || $busRes === false) {
            $this->ReceiveModel->rollback();
            $this->BusinessModel->rollback();
            $this->OrderModel->rollback();
            $this->error('预约失败');
            exit;
        }else{
            $this->OrderModel->rollback();
            $this->BusinessModel->rollback();
            $this->ReceiveModel->rollback();
            $this->success('预约成功');
            exit;
        }
    }
}
